package org.lewis.woman.controllers;

import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.lewis.common.domain.Tag;
import org.lewis.common.service.TagService;
import org.lewis.common.utils.WebUtils;

import com.tocersoft.framework.core.annotations.Controller;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.web.annotations.Mapping;
import com.tocersoft.framework.web.annotations.NameSpace;
import com.tocersoft.framework.web.renderer.Renderer;
import com.tocersoft.framework.web.renderer.TextRenderer;

@Controller
@NameSpace("/admin/tag")
public class TagController {

	@Injection
	TagService tagService;

	@Mapping("/list")
	public Renderer getJsonListByPage() throws JSONException {
		JSONArray json = new JSONArray();
		List<Tag> result = tagService.queryAll(false);
		for (Tag tag : result) {
			JSONObject obj = new JSONObject();
			obj.put("id", tag.getId());
			obj.put("name", tag.getName());
			obj.put("songs", tag.getSongs());
			obj.put("rank", tag.getRank());
			obj.put("type", tag.getTypeStr());
			json.put(obj);
		}
		return new TextRenderer(json.toString());
	}

	@Mapping("/add")
	public Renderer doAdd() throws Exception {
		String name = WebUtils.getParameter("name");
		String rank = WebUtils.getParameter("rank");
		String type = WebUtils.getParameter("type");
		if (StringUtils.isEmpty(name)) {
			throw new Exception("Name must be not empty");
		}
		Tag tag = new Tag();
		tag.setName(name);
		tag.setType(Integer.parseInt(type));
		if (StringUtils.isEmpty(rank)) {
			rank = "0";
		}
		tag.setRank(Integer.parseInt(rank));
		tag.setSongs(0L);
		tagService.addTag(tag);

		return null;
	}

	@Mapping("/update")
	public Renderer doUpdate() throws Exception {
		String id = WebUtils.getParameter("id");
		String name = WebUtils.getParameter("name");
		String rank = WebUtils.getParameter("rank");
		String type = WebUtils.getParameter("type");
		if (StringUtils.isEmpty(name)) {
			throw new Exception("Name must be not empty");
		}
		if (StringUtils.isEmpty(rank)) {
			rank = "0";
		}
		tagService.updateTag(Long.valueOf(id), name, Integer.parseInt(rank),Integer.parseInt(type));

		return null;
	}

}
